/**
 * 定义变量
 */
var statebar; 	// 顶部区域
var toolbar;	// 输入区域
var logbox;		// 消息区域
var inputbox;	// 输入框
var lastTalkId; // 最后一条消息ID
var totalMemoryDom; // 总内存
var freeMemoryDom;	// 空闲内存
var maxMemoryDom;	// 最大内存
var usedMemoryDom;	// 使用中的内存
var connectorCountDom;	// 连接数量
var startupDom;	// 系统已运行时间
var workStyleDom;	// 连接状态
var maxLogCount = 100;	// 最大输入长度

/**
 * 初始化
 */
function init(){
    statebar = document.getElementById("statebar");
    toolbar = document.getElementById("toolbar");
    logbox = document.getElementById("logbox");
    inputbox = document.getElementById("inputbox");
    totalMemoryDom = document.getElementById("totalMemory");
    freeMemoryDom = document.getElementById("freeMemory");
    maxMemoryDom = document.getElementById("maxMemory");
    usedMemoryDom = document.getElementById("usedMemory");
    connectorCountDom = document.getElementById("connectorCount");
    workStyleDom = document.getElementById("workStyle");
    startupDom = document.getElementById("startup");
//    windowResize();
//    window.onresize = windowResize;
    // 引擎事件绑定
    JS.Engine.on({
        start: function(cId, aml, engine){
            var style = engine.getConnector().workStyle;
            style = style === 'stream' ? '长连接' : '长轮询';
            workStyleDom.innerHTML = style;
        },
        stop: function(cause, url, cId, engine){
            workStyleDom.innerHTML = '<span class="warning">已停止<a href="javascript:start();" >(重连)</a></span>';
        },
        t: function(data, timespan, engine){
            switch (data.type) {
                case 'talk': // 收到聊天消息
                    onMessage(data, timespan);
                    break;
                case 'up': // 上线
                    onJoin(data, timespan);
                    break;
                case 'down': // 下线
                    onLeft(data, timespan);
                    break;
                case 'health':
                    onHealthMessage(data, timespan);
                    break;
                default:
            }
        }
    });
	// 开启连接
	start();
}

/**
 * 开启连接
 */
function start(){
    JS.Engine.start('CometServlet');
    inputbox.focus();
}

/**
 * 发送聊天信息动作
 * @param {Object} text
 */
function send(text){
    if (!JS.Engine.running) 
        return;
    text = text.trim();
    if (!text) 
        return;
    var id = JS.Engine.getId();
    var param = "id=" + id + '&text=' + encodeURIComponent(text);
    JS.AJAX.post('/action/interact/ChatServlet?cmd=talk', param, function(){
        inputbox.value = '';
    });
}

function windowResize(){
    var offset = 2;
    var other = statebar.offsetHeight + toolbar.offsetHeight + offset;
    logbox.style.height = document.documentElement.clientHeight - other + 'px';
}

/**
 * 系统健康信息
 * @param {Object} data
 * @param {Object} timespan
 */
function onHealthMessage(data, timespan){
    var totalMemory = data.totalMemory;
    var freeMemory = data.freeMemory;
    var maxMemory = data.maxMemory;
    var usedMemory = data.usedMemory;
    var startup = data.startup;
    var connectorCount = data.connectorCount + '个';
    totalMemoryDom.innerHTML = totalMemory + 'M';
    freeMemoryDom.innerHTML = freeMemory + 'M';
    maxMemoryDom.innerHTML = maxMemory + 'M';
    usedMemoryDom.innerHTML = usedMemory + 'M';
    connectorCountDom.innerHTML = connectorCount;
    startupDom.innerHTML = startup;
}

/**
 * 用户聊天通知
 * @param {Object} data
 * @param {Object} timespan
 */
function onMessage(data, timespan){
    var id = data.id;
    var name = data.name || '';
    name = name.HTMLEncode();
    var text = data.text || '';
    text = text.HTMLEncode();
    var t = data.transtime;
    var str;
    if (lastTalkId == id) {
        str = ['<div class="usermessage">', '<blockquote>', text, '</blockquote>', '</div>'];
    }
    else {
        str = ['<div class="usermessage">', t, '<span class="user">【', name, '】</span><blockquote>', text, '</blockquote>', '</div>'];
    }
    checkLogCount();
    logbox.innerHTML += str.join('');
    lastTalkId = id;
    moveScroll();
}

/**
 * 用户上线通知
 * @param {Object} data
 * @param {Object} timespan
 */
function onJoin(data, timespan){
    var id = data.id;
    
    var name = data.name || '';
    name = name.HTMLEncode();
    var t = data.transtime;
    var str = ['<div class="sysmessage">', t, '【', name, '】加入了聊天。 ', '</div>'];
    checkLogCount();
    logbox.innerHTML += str.join('');
    lastTalkId = null;
    moveScroll();
}

/**
 * 用户下线通知
 * @param {Object} data
 * @param {Object} timespan
 */
function onLeft(data, timespan){
    var id = data.id;
    var name = data.name || '';
    name = name.HTMLEncode();
    var t = data.transtime;
    var str = ['<div class="sysmessage">', t, '【', name, '】离开了。', '</div>'];
    checkLogCount();
    logbox.innerHTML += str.join('');
    lastTalkId = null;
    moveScroll();
}

/**
 * 回车事件
 * @param {Object} event
 */
function onSendBoxEnter(event){
    if (event.keyCode == 13) {
        var text = inputbox.value;
        send(text);
        return false;
    }
}

/**
 * 移动滚动条
 */
function moveScroll(){
    logbox.scrollTop = logbox.scrollHeight;
    inputbox.focus();
}

/**
 * 检测输出长度
 */
function checkLogCount(){
    var count = logbox.childNodes.length;
    if (count > maxLogCount) {
        var c = count - maxLogCount;
        for (var i = 0; i < c; i++) {
            logbox.removeChild(logbox.firstChild);
        }
    }
}

/**
 * HTML编码
 */
String.prototype.HTMLEncode = function(){
    var temp = document.createElement("div");
    (temp.textContent != null) ? (temp.textContent = this) : (temp.innerText = this);
    var output = temp.innerHTML;
    temp = null;
    return output;
};

/**
 * HTML解码
 */
String.prototype.HTMLDecode = function(){
    var temp = document.createElement("div");
    temp.innerHTML = this;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
};

/**
 * 字符格式化
 */
String.prototype.trim = function(){
    return this.replace(/^\s+|\s+$/g, '');
};
